<template>
  <el-dialog
      title="检查任务"
      v-model="dialogVisible"
      width="1400px"
      :close-on-click-modal="false"
      @close="handleDialogClose"
  >
    <div class="task-header">
      <h3>{{ doctor?.doctorName }}的检查任务</h3>
      <div class="search-group">
        <el-date-picker
            v-model="searchParams.date"
            type="date"
            placeholder="选择日期"
            value-format="YYYY-MM-DD"
            :locale="zhCn"
        />
        <el-input
            v-model="searchParams.elderName"
            placeholder="请输入姓名"
            clearable
            style="width: 200px"
        />
        <!-- 搜索按钮 -->
        <el-button type="primary" @click="handleSearch">搜索</el-button>

        <!-- 重置按钮 -->
        <el-button @click="resetSearch">重置</el-button>
      </div>
      <el-button type="primary" :icon="Plus" @click="handleAddTask">添加任务</el-button>
    </div>
    <el-table
        :data="checkTaskList"
        style="width: 100%"
        v-loading="loading"
        border
        stripe
    >
      <el-table-column prop="date" label="检查日期" align="center" min-width="120"/>
      <el-table-column prop="checkTypes.name" label="检查类型" align="center" min-width="120"/>
      <el-table-column prop="elderName" label="老人姓名" align="center" min-width="120"/>
      <el-table-column label="完成状态" align="center" width="120">
        <template #default="{ row }">
          <el-tag :type="row.finish ? 'success' : 'warning'">
            {{ row.finish ? '已完成' : '未完成' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="是否异常" align="center" width="120">
        <template #default="{ row }">
          <el-tag :type="row.hasQuestion ? 'danger' : 'success'">
            {{ row.hasQuestion ? '异常' : '正常' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="result" label="检查结果" align="center" min-width="300" show-overflow-tooltip/>
      <el-table-column label="操作" align="center" width="200" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" :icon="Edit" @click="handleUpdateTask(row)">编辑</el-button>
          <el-button type="danger" :icon="Delete" @click="handleDeleteTask(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 检查任务编辑表单对话框 -->
    <check-task-form-dialog
        v-if="showTaskForm"
        v-model="showTaskForm"
        :task="currentTask"
        :check-types="checkTypes"
        :doctor-id="doctor?.id"
        :doctor-community-id="doctor?.communityId"
        @success="handleSuccess"
    />
  </el-dialog>
</template>

<script setup lang="ts">
import {ref, computed, watch} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {Edit, Delete, Plus} from '@element-plus/icons-vue'
import type {Doctor} from '@/types/doctor'
import type {CheckTask} from '@/types/checkTask'
import type {Elder} from '@/types/elder'
import type {CheckType} from '@/types/checkType'
import {getDoctorCheckTasks, deleteDoctorCheckTask, getCheckTypes, DoctorAndElderAndDate} from '@/api/doctor'
import {getAllElders} from '@/api/elder'
import CheckTaskFormDialog from './CheckTaskFormDialog.vue'
import zhCn from "element-plus/es/locale/lang/zh-cn";

const searchParams = ref({
  date: '',
  elderName: ''
})

// 搜索方法
const handleSearch = () => {
  fetchElderCheckTaskList()
}

const fetchElderCheckTaskList = async () => {
  const res = await getDoctorCheckTasks(<DoctorAndElderAndDate>{
    doctorId: props.doctor?.id,
    date: searchParams.value.date,
    elderName: searchParams.value.elderName
  })
  checkTaskList.value = res.map(task => {
    const elder = elderList.value.find(e => e.id === task.elderId)
    return {
      ...task,
      elderName: elder ? elder.elderName : '未知'
    }
  })
}

// 对话框关闭处理
const handleDialogClose = () => {
  // 重置搜索条件
  searchParams.value = {
    date: '',
    elderName: ''
  }
}


// 重置搜索
const resetSearch = async () => {
  searchParams.value = {
    date: '',
    elderName: ''
  };
  await fetchCheckTaskList()
}

const props = defineProps<{
  modelValue: boolean
  doctor?: Doctor
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'success'): void
}>()

const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const loading = ref(false)
const checkTaskList = ref<CheckTask[]>([])
const elderList = ref<Elder[]>([])
const showTaskForm = ref(false)
const currentTask = ref<CheckTask | undefined>()
const checkTypes = ref<CheckType[]>([])

// 获取检查类型列表
const fetchCheckTypes = async () => {
  try {
    checkTypes.value = await getCheckTypes()
  } catch (error) {
    console.error('获取检查类型失败:', error)
  }
}

// 获取老人列表
const fetchElderList = async () => {
  try {
    elderList.value = await getAllElders()
  } catch (error) {
    console.error('获取老人列表失败:', error)
  }
}

// 获取检查任务列表
const fetchCheckTaskList = async () => {
  if (!props.doctor) return

  loading.value = true
  try {
    // 先获取老人列表和检查类型列表
    await Promise.all([fetchElderList(), fetchCheckTypes()])

    // 获取检查任务列表
    const tasks = await getDoctorCheckTasks({doctorId: props.doctor.id})
    // 为每个检查任务添加老人姓名
    checkTaskList.value = tasks.map(task => {
      const elder = elderList.value.find(e => e.id === task.elderId)
      return {
        ...task,
        elderName: elder ? elder.elderName : '未知'
      }
    })
  } catch (error) {
    console.error('获取检查任务失败:', error)
  } finally {
    loading.value = false
  }
}

// 1. 修改handleUpdateTask方法（深拷贝保证数据独立性）
const handleUpdateTask = (row: CheckTask) => {
  currentTask.value = {
    ...row,
    // 确保嵌套对象也响应式
    checkTypes: row.checkTypes ? {...row.checkTypes} : undefined
  }
  showTaskForm.value = true
}

// 删除检查任务
const handleDeleteTask = async (row: CheckTask) => {
  try {
    await ElMessageBox.confirm('删除后将无法恢复该检查任务，是否确认删除？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      draggable: true,
      closeOnClickModal: false
    })
    await deleteDoctorCheckTask(row.id)
    ElMessage.success('删除成功')
    await fetchCheckTaskList()
  } catch (error) {
    if (error === 'cancel') {
      ElMessage.info('已取消删除')
    }
  }
}

// 编辑成功回调
const handleSuccess = () => {
  fetchCheckTaskList()
}

// 添加检查任务
const handleAddTask = () => {
  currentTask.value = undefined
  showTaskForm.value = true
}

// 监听对话框显示状态
watch(dialogVisible, (newVal: boolean) => {
  if (newVal) {
    fetchCheckTaskList()
  }
})
</script>

<style scoped>

.search-group {
  display: flex;
  align-items: center;
  gap: 10px; /* 统一设置元素间间距 */
}

/* 统一输入框和按钮的宽度和间距 */
.search-group .el-input,
.search-group .el-select,
.search-group .el-button {
  margin: 0; /* 清除默认margin */
}

:deep(.el-dialog__header) {
  margin: 0;
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-dialog__footer) {
  padding: 20px;
  border-top: 1px solid #ebeef5;
}

.task-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.task-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: normal;
  color: #303133;
}

:deep(.el-button) {
  transition: all 0.3s;
  padding: 0 15px;
  font-size: 14px;
}

:deep(.el-button:hover) {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

:deep(.el-button--primary) {
  background-color: #409eff;
  border-color: #409eff;
  color: #fff;
}

:deep(.el-button--primary:hover) {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

:deep(.el-button--danger) {
  background-color: #f56c6c;
  border-color: #f56c6c;
  color: #fff;
}

:deep(.el-button--danger:hover) {
  background-color: #f78989;
  border-color: #f78989;
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
}

:deep(.el-table td) {
  padding: 12px 0;
}

:deep(.el-table__row:hover) {
  background-color: #f5f7fa !important;
}

:deep(.el-table--border) {
  border: 1px solid #ebeef5;
}

:deep(.el-table--border th),
:deep(.el-table--border td) {
  border-right: 1px solid #ebeef5;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-tag) {
  border-radius: 4px;
  padding: 0 8px;
  height: 24px;
  line-height: 24px;
}

:deep(.el-tag--success) {
  background-color: #f0f9eb;
  border-color: #e1f3d8;
  color: #67c23a;
}

:deep(.el-tag--warning) {
  background-color: #fdf6ec;
  border-color: #faecd8;
  color: #e6a23c;
}

:deep(.el-tag--danger) {
  background-color: #fef0f0;
  border-color: #fde2e2;
  color: #f56c6c;
}
</style> 